﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Domain.Events;
using Ncqrs.Eventing.ServiceModel.Bus;
using ReadModel.ViewModels;

namespace ReadModel.Denormalizers
{
    public class NoteListItemDenormalizer : IEventHandler<NoteCreatedEvent>
        , IEventHandler<ImportanceChangedEvent>
    {
        readonly EFReadContext _context;

        public NoteListItemDenormalizer()
        {
            _context = new EFReadContext();
        }

        public void Handle(NoteCreatedEvent @event)
        {
            var instance = new NoteListItem { NoteId = @event.NoteId, Importance = @event.Importance };
            instance.Summary = @event.Text.Length > 5 ? string.Concat(@event.Text.Substring(0, 5), "...") : @event.Text;

            _context.NoteListItems.Add(instance);
            _context.SaveChanges();
        }

        public void Handle(ImportanceChangedEvent @event)
        {
            var instance = _context.NoteListItems.Find(@event.NoteId);
            instance.Importance = @event.Importance;

            _context.SaveChanges();
        }
    }
}
